package com.bt.lms.ui.action.registration.stu;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.RegStuBizTypeConstant;
import com.bt.lms.entity.RegStuInfo;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.page.stu.PageAddStuInfo;
import com.bt.lms.ui.page.stu.vo.RegistrationStuVo;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.FileChooser;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 新增学生信息界面选择上传照片按钮事件
 */
public class PageAddStuSelectPhotoFileBtnAction implements EventHandler {

    @Override
    public void handle(Event event) {
        //文件选择器
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择照片文件");
        File photoFilePath = fileChooser.showOpenDialog(null);
        String fileName = null;//获取文件名
        try {
            fileName = photoFilePath.getName();
        } catch (Exception e) {
            return;
        }

        //如果文件不是以.jpg .jpeg .gif .pdf .png     endsWith   以...后缀结尾   !非
        if (!fileName.endsWith(".jpg") && !fileName.endsWith(".jpeg") && !fileName.endsWith(".gif") && !fileName.endsWith(".pdf") && fileName.endsWith(".png")) {

            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText("文件格式有误，仅支持jpg、jpeg、gif、pdf、png");
            alert.showAndWait();
        }
        int fileLength = fileName.length();
        if (fileLength > 50) {//文件长度大于50


            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText("文件大小不能超过5MB");
            alert.showAndWait();

        }

        try {
            //读取流
            FileInputStream fileIn = new FileInputStream(photoFilePath);
            //读取缓冲区
            byte[] buffer = new byte[1024];
            fileIn.read(buffer);

            //文件集合
            List<String> fileUrls = new ArrayList<>();
            fileUrls.add(photoFilePath.toString());

            RegistrationStuVo registrationStuVo = new RegistrationStuVo();
            registrationStuVo.setUrl(fileUrls);


            //组包
            byte[] bytes = getBytes(photoFilePath);

            //获取网络
            Socket socket = getNet();

            //发送消息
            boolean sendReqMsg = sendReqMsg(socket, bytes, photoFilePath);

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    /**
     * 发送消息
     *
     * @param socket 网络
     * @param bytes  bytes数组
     * @return 是否成功
     */
    private boolean sendReqMsg(Socket socket, byte[] bytes, File photoFilePath) {

        try {
            //输出流
            OutputStream out = socket.getOutputStream();
            out.write(bytes);
            out.flush();


            //接收响应消息
            RespMsg acceptRespMsg = acceptRespMsg(socket, photoFilePath);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return true;
    }

    /**
     * 接收响应消息
     *
     * @param socket        网
     * @param photoFilePath 照片路径
     * @return 响应消息
     */
    private RespMsg acceptRespMsg(Socket socket, File photoFilePath) {

        RespMsg respMsg = null;
        //读取流
        try {
            InputStream in = socket.getInputStream();
            byte[] buffer = new byte[1024];
            in.read(buffer);

            //响应消息
            respMsg = RespMsg.toRespMsg(buffer);
            //获取到响应消息的数据
            String data = respMsg.getData();

            //如果数据不为空弹框
            if (data != null) {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("个人照片上传");
                alert.setContentText("个人照片上传成功，请查看");
                alert.show();

                //文件路径分割
                String url = "file:" + File.separator + photoFilePath.toString();
                File file = new File(url);
                //把图片显示出来.
                Image image = new Image(file.toString());
                ImageView imageView = new ImageView(image);
                imageView.setFitWidth(300);
                imageView.setFitHeight(200);

                //放到界面上
                ObservableList<Node> children = PageAddStuInfo.photoHBox.getChildren();
                if (children.size() == 2) {
                    children.add(1, imageView);

                } else if (children.size() == 3) {
                    children.set(1, imageView);

                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return respMsg;
    }

    /**
     * 获取网络
     *
     * @return
     */
    private Socket getNet() {

        String ip = "127.0.0.1";
        Integer port = 8888;
        Socket socket = null;
        try {
            socket = new Socket(ip, port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return socket;
    }

    /**
     * 组包
     *
     * @param photoFilePath 个人照片路径
     * @return byte数组
     */
    private byte[] getBytes(File photoFilePath) {

        //请求消息
        ReqMsg reqMsg = new ReqMsg();

        //报名学员信息
        RegStuInfo regStuInfo = new RegStuInfo();

        //把个人照片路径带走
        regStuInfo.setPhotoUrl(photoFilePath.toString());

        //业务类型
        reqMsg.setBizType(RegStuBizTypeConstant.STU_REG_INFO_ADD);

        String phoneFilePathStr = JSON.toJSONString(regStuInfo);

        //把数据带走
        reqMsg.setData(phoneFilePathStr);

        byte[] bytes = reqMsg.toBytes();


        return bytes;
    }
}
